package gl.java.upload;

import gl.java.sms.Applictation;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class APKServletUpload extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final String CONTENT_TYPE = "text/html; charset=UTF-8";

	// Initialize global variables
	public void init() throws ServletException {

	}

	// Process the HTTP Get request
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType(CONTENT_TYPE);
		try {// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Configure a repository (to ensure a secure temp location is used)
			ServletContext servletContext = this.getServletConfig()
					.getServletContext();
			File repository = (File) servletContext
					.getAttribute("javax.servlet.context.tempdir");
			factory.setRepository(repository);

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Parse the request
			List<FileItem> items = upload.parseRequest(request);
			Iterator<FileItem> iter = items.iterator();
			APK av = new APK();

			while (iter.hasNext()) {
				FileItem item = iter.next();
				processFormField(item, av);
			}
			writeResponse(response, "upload " + av.getName() + " ok");
		} catch (Exception e) {
			e.printStackTrace(System.err);
			writeResponse(response, e.getMessage(), true);
		} finally {
			sendResponse(response);
		}

	}

	private void processFormField(FileItem item, APK av) throws Exception {
		// Process a file upload
		if (!item.isFormField()) {
			String fieldName = item.getFieldName();
			String fileName = item.getName();
			// String contentType = item.getContentType();
			// boolean isInMemory = item.isInMemory();
			long sizeInBytes = item.getSize();
			if (fileName!=null&&!"".equals(fileName)) {
				File uploadedFile = new File(Applictation.path_file + fileName);
				System.out.println("key:" + fieldName + "  >filename  :"
						+ fileName + ">  savepath:" + uploadedFile + ">size>"
						+ sizeInBytes);
				item.write(uploadedFile);

				if (fieldName.equals("name")) {
					final String _fileName = fileName;
					av.setUrl(_fileName);
				}
			}
		} else {// 其他非数据字段
			String fieldName = item.getFieldName();
			String fileName = new String(item.get(), "UTF-8");
			System.out.println("from :" + fieldName + "  >filename  :"
					+ fileName);
			if (fieldName.equals("uploadName")) {
				av.setName(fileName);
			} else if (fieldName.equals("about")) {
				av.setAbout(fileName);
			} else if (fieldName.equals("version")) {
				av.setVersion(fileName);
			}
		}

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	// Clean up resources
	public void destroy() {
	}
}